package com.ray.service;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ray.bean.ExpectDateBean;
import com.ray.bean.OrderBean;
import com.ray.bean.ProcessBean;
import com.ray.bean.ReportBean;
import com.ray.bean.WorkshopProductionCycleBean;
import com.ray.mapper.ExpectDateMapper;
import com.ray.util.TimeAndUnix;

@Service
public class ExpectDateService {

	@Autowired
	ExpectDateMapper expectDateMapper;
	@Autowired
	BasicDataService basicDataService;
	
	public ExpectDateBean getExpectDate(Map map) throws ParseException {
		ExpectDateBean ex=new ExpectDateBean();
	    //获取订单信息
		OrderBean order=expectDateMapper.getOrderBean(map);
		if(order.getSort()<0 || order.getOutCount() >=order.getOrderCount()) {
			ex.setEstimateTime("已完成");
			ex.setProposalPurchaseTime("已完成");
			return ex;
		}
		Double dayCapacity=1.0;//日产能
		long orderCount=order.getOrderCount();//订单数
		int restType=order.getRestType();//休息类型
		//获取本订单数量
		//获取订单部门id
	    String deptId=order.getDeptId();
	    if("".equals(deptId)|| null==deptId) {
	    	ex.setIsSetOrderDept(2);//未设置订单部门
	    	deptId="";
	    }
	    map.put("deptId", deptId);
	    if( order.getDeptDayCapacity()==1.0|| order.getDeptDayCapacity()==0.0) {
	    	ex.setIsSetDayCapacity(2);
	    	order.setDeptDayCapacity(1);
	    }
	    Double orderFlowCount=order.getProductionCycle();//部门生产周期
		if(orderFlowCount==null || orderFlowCount==0) {
			ex.setIsSetProcedutionFlow(2);//未设置部门流程周期
		}
	    dayCapacity=order.getDeptDayCapacity();
	    
		//获取订单之前单总和
		long beforeOrderCount=0;
		map.put("orderSort", order.getSort());
		//获取再此订单之前的订单编号
	    List<OrderBean> orderList=expectDateMapper.getBeforeOrderList(map);
	    beforeOrderCount = orderList.stream().map(OrderBean::getOrderCount).reduce( 0, Integer::sum);
//        for(OrderBean orderBean:orderList) {
//        	beforeOrderCount+=orderBean.getOrderCount();
//        }
//        map.put("orderList", orderList);
	    //获取之前订单已完成总和
	    long beforeFinishCount=orderList.stream().map(OrderBean::getOrderCount).reduce( 0, Integer::sum);
//	    if(orderList != null && orderList.size()>0) {
//	    	beforeFinishCount=(int) isNullToZero(expectDateMapper.getBeforeFinishCount(map));
//	    }
	    //得到未完成总和
	    Double beforeNotFinishCount=isNullToZero((double) (beforeOrderCount-beforeFinishCount));
	    
	    //获取订单采购周期
	    Integer orderPurchaseFlow=0;
	    orderPurchaseFlow=(int) isNullToZero(expectDateMapper.getOrderPurchaseFlow(map));
	    
	    
	    //获取之前订单需生产天数
	    double beforeDay=0.0;
	    switch(restType) {
	        case 0:beforeDay=beforeNotFinishCount/dayCapacity;break;//没有休息
	        case 1:beforeDay=beforeNotFinishCount/dayCapacity*30/29;break;//月休一天
	        case 2:beforeDay=beforeNotFinishCount/dayCapacity*15/14;break;//月休两天
	        case 3:beforeDay=beforeNotFinishCount/dayCapacity*10/9;break;//月休三天
	        case 4:beforeDay=beforeNotFinishCount/dayCapacity*7/6;break;//单休
	        case 5:beforeDay=beforeNotFinishCount/dayCapacity*7/5.5;break;//1.5休
	        case 6:beforeDay=beforeNotFinishCount/dayCapacity*7/5;break;//双休
	    }
	    beforeDay=(double)Math.round(beforeDay*100)/100;
	    //本订单需要生产天数
	    double orderDay=orderCount/dayCapacity;
	    switch(restType) {
	        case 0:break;//没有休息
	        case 1:orderDay=orderDay*30/29;break;//月休一天
	        case 2:orderDay=orderDay*15/14;break;//月休两天
	        case 3:orderDay=orderDay*10/9;break;//月休三天
	        case 4:orderDay=orderDay*7/6;break;//单休
	        case 5:orderDay=orderDay*7/5.5;break;//1.5休
	        case 6:orderDay=orderDay*7/5;break;//双休
        }
	    orderDay=(double)Math.round(orderDay*100)/100;
	    //订单实际生产天数
	    double orderRechDay=0.0;
	    
	    if(orderDay>orderFlowCount) {
	    	orderRechDay=orderPurchaseFlow>beforeDay?orderDay+orderPurchaseFlow:orderDay+beforeDay;
	    }else {
	    	orderRechDay=orderPurchaseFlow>beforeDay?orderFlowCount+orderPurchaseFlow:orderFlowCount+beforeDay;
	    }
	    
	    int proposalPurchaseDay=beforeDay-orderPurchaseFlow>0?new Double(Math.floor(beforeDay-orderPurchaseFlow)).intValue():0;
	    
	    ExpectDateBean expectDate=new ExpectDateBean();
	    ex.setBeforeDay(beforeDay);
	    ex.setBeforeNotFinishCount(beforeNotFinishCount);
	    ex.setDayCapacity(dayCapacity);
	    ex.setOrderCount(orderCount);
	    ex.setOrderDay(orderDay);
	    ex.setProcurementCycles(orderPurchaseFlow);
	    ex.setReachDay(orderRechDay);
	    ex.setBeforeOrderCount(orderList.size());
	    ex.setEstimateTime(TimeAndUnix.getBeforeDay(new Double(Math.floor(orderRechDay)).intValue(), ""));
	    ex.setProposalPurchaseTime(TimeAndUnix.getBeforeDay(proposalPurchaseDay,""));
	    ex.setOrderFlowCount(orderFlowCount);
		//如果采购周期为0
	    if(orderPurchaseFlow<=0) {
	    	ex.setProposalPurchaseTime("已完成");
		}
	    return ex;
	}

	//获取工序生产时间
	public String getProcedureExpectDate(Map map) throws ParseException {
		String returnTime="";
		//1，先判断次订单是否开始生产
		     ReportBean rb=expectDateMapper.getLaseReport(map);
		     //-->是
		     if(null!=rb) {
		    	 //判断本车间是否开始生产
		    	 map.put("timeWorkShop", map.get("workShop"));
		    	 ReportBean rb2=expectDateMapper.getLaseReport(map);
		    	 if(rb2 !=null) {
		    		 //-->是   得到本工序预计生产时间
		    		 returnTime=this.knowTimeAndPurcedureGetTime(rb2,map);
		    	 }else {
		    		 //-->否   获取本车间第一道工序生产时间
		    		    //1.获取目前车间生产还要多久
		    		    Map workMap=new HashMap();
		    		    workMap.put("orderId", map.get("orderId"));
		    		    workMap.put("workShop", rb.getWorkShopName());
		    		    workMap.put("workShop2", map.get("workShop"));
		    		    workMap.put("report", rb);
		    		    Integer start = expectDateMapper.getStartSort(workMap);
		    		    start=start==null?0:start;
		    		    workMap.put("startSort", start);
		    		    double xuTime=expectDateMapper.getWorkSumTime(workMap);
		    		    workMap.remove("startSort");
		    		    double sumTime=expectDateMapper.getWorkSumTime(workMap);
		    		    int workDay=expectDateMapper.getWorkShopDay(workMap);
		    		    //在次车间还需生产天数
		    		    double thisWorkDays=xuTime/sumTime*workDay;
		    		    //2.获取本车间第一道工序生产时间
		    		    //生产本车间还需要多少天
		    		    workMap.put("sort", start);
		    		    double workTurnDay=expectDateMapper.getWorkTurnDay(workMap);
		    		    workTurnDay=workTurnDay+thisWorkDays;
		    		    //开始生产本车间日期
		    		    String day=TimeAndUnix.timeAddDay(rb.getTouchTime(),new Double(Math.floor(workTurnDay)).intValue());
		    		    //本车间生产的第一道工序
		    		    String procedureId=expectDateMapper.getFistProcedure(map);
		    		    rb.setTouchTime(day);
		    		    rb.setProcedur(procedureId);
		    		    returnTime= this.knowTimeAndPurcedureGetTime(rb,map);
		    	 }
		     }else {//-->否
		    	 rb=new ReportBean();
		    	 //获取本订单预计完成时间
		    	 ExpectDateBean expectDate=this.getExpectDate(map);
		    	 String finishTime=expectDate.getEstimateTime();
		    	 if(finishTime.equals("已完成")) {
		    		 return "此订单已完成";
		    	 }
		    	 //通过预计完成时间反推本车间开始生产时间，得到本车间第一道工序生产时间
		    	 //得到本订单所有  在本车间之后的   车间   最大的  生产周期
		    	 double maxAfterDays=expectDateMapper.getMaxAfterDays(map);
		    	 
		    	 //得到本车间第一道工序
		    	 String procedureId=expectDateMapper.getFistProcedure(map);
		    	 rb.setProcedur(procedureId);
		    	 rb.setTouchTime(TimeAndUnix.timeAddDay(finishTime,-new Double(Math.floor(maxAfterDays)).intValue()));
		    	 rb.setWorkShopName(map.get("workShop").toString());
		    	 returnTime=this.knowTimeAndPurcedureGetTime(rb, map);
		     }
		return returnTime;
	}
	
//	知道本车间生产第一道工序和时间，获取本工序预计生产时间
	private String knowTimeAndPurcedureGetTime(ReportBean rb,Map map) throws ParseException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		//获取车间数据（周转余量）
		WorkshopProductionCycleBean wpcb=basicDataService.getWCById(rb.getWorkShopName());
		map.remove("report");
		map.put("report", rb);
		int startSort=expectDateMapper.getStartSort(map);
		int endSort=expectDateMapper.getEndSort(map);
		if(startSort>=endSort) {
			return rb.getTouchTime();
		}else {
			map.put("startSort", startSort);
			map.put("endSort", endSort);
            //获取车间生产周期
			double workDay=wpcb.getProcessCycle();
			double sumUnitTime=expectDateMapper.getWorkSumTime(map);
			map.remove("startSort");
			map.remove("endSort");
			double sumTime=expectDateMapper.getWorkSumTime(map);
			//生产到本工序时间为周转余量/日产能+（日产能*周期-周转余量）/日产能*单付时间/单付时间总和
			double yy=wpcb.getTuenoverTwo()/wpcb.getDailyCapacity()+(wpcb.getDailyCapacity()*wpcb.getProcessCycle()-wpcb.getTuenoverTwo())/wpcb.getDailyCapacity()*sumUnitTime/sumTime;
			int xx=new Double(Math.floor(yy)).intValue();
	        return TimeAndUnix.timeAddDay(rb.getTouchTime(),xx);
		}
	}
	
	
	private double isNullToZero(Object object) {
		if(null==object) {
			return 0;
		}else {
			return Double.parseDouble(object.toString());
		}
	}
	
	
//	//自动设时间
//	public void setSort(Map map) {
//		List<OrderBean> orderList=expectDateMapper.getSortOrder(map);
//		int i=1;
//		for(OrderBean order:orderList) {
//			order.setSort(i);
//			i++;
//		}
//		expectDateMapper.setSort(orderList);
//	}

}
